<script lang="ts" setup>
import { ref, reactive, watch, computed, defineEmits, h } from 'vue'
import { useDebounceFn } from '@vueuse/core'
import { useVbenModal } from '@vben/common-ui'

import { Button, message, DatePicker, Input, Switch } from 'ant-design-vue'

import type { VxeGridProps } from '#/adapter/vxe-table'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { useVbenForm } from '#/adapter/form'
import { getMstockinInfo, doMstockinAdd, doMstockinEdit, AuditMstockIn, ReverseMstockIn, getPlanGoods, getPlanList, getProcessList, getWarehouseList, getSupplyList } from '#/api/mstockin'
import { getDict, getAdminList } from '#/api/common'
import MaterialSku from '#/views/backend/modules/materialSku.vue'
import dayjs from 'dayjs'
import Plan from '../../modules/plan.vue'

/**
 * 表格行数据类型定义
 */
interface RowType {
  goods_no?: string
  goods_name?: string
  color_code?: string
  color_name?: string
  size_name?: string
  num?: string | number
  bad_num?: string | number
  weight?: string | number
  price?: string | number
  amount?: string | number
  remark?: string
  _X_ROW_KEY?: string
}

const mstockinId = ref<number>()
const routerData = ref()
const formData = ref<any>({})
const dict = ref<any>({})
const processList = ref<any>([])
const isDisabled = ref(true)
const emit = defineEmits(['fetchData'])

// 搜索关键词
const keyword = ref<Record<string, any>>({
  supply_id: '',
  Planid: '',
  warehouse_id: '',
})

// 获取入库单详情
const fetchData = async () => {
  const { row } = await getMstockinInfo({ id: mstockinId.value })
  formApi.setValues(row)
  formData.value = { ...row } // 保留旧逻辑兼容
  // 使用 setGridOptions 更新表格数据
  if (gridApi) {
    gridApi.setGridOptions({
      data: row.sku_list || [],
    })
  }

  // 确保 row 存在且有值再进行处理
  if (row && typeof row === 'object') {
    Object.keys(keyword.value).forEach((key: string) => {
      if (row[key]) {
        keyword.value[key] = 'initValue:' + row[key]
      }
    })
  }
}

/**
 * 获取加工厂选项
 */
const supplyOptions = async ({ keyword = '' }: Record<string, any>) => {
  let quick_search = ''
  let initValue = ''
  let initKey = 'id'

  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '')
  } else {
    quick_search = keyword
  }

  const { list } = await getSupplyList({
    quick_search: quick_search,
    page: 1,
    limit: 30,
    initKey: initKey,
    initValue: initValue,
    select: true,
  })

  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }))
}

/**
 * 获取仓库选项
 */
const warehouseOptions = async ({ keyword = '' }: Record<string, any>) => {
  let quick_search = ''
  let initValue = ''
  let initKey = 'id'

  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '')
  } else {
    quick_search = keyword
  }

  const { list } = await getWarehouseList({
    quick_search: quick_search,
    page: 1,
    limit: 30,
    initKey: initKey,
    initValue: initValue,
    select: true,
  })

  return list.map((item: any) => ({
    label: item.label,
    value: item.value,
  }))
}

/**
 * 获取生产制单选项
 */
const planOptions = async ({ keyword = '' }: Record<string, any>) => {
  let quick_search = ''
  let initValue = ''
  let initKey = 'production_sn'

  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '')
  } else {
    quick_search = keyword
  }

  const { list } = await getPlanList({
    quick_search: quick_search,
    page: 1,
    limit: 30,
    initKey: initKey,
    initValue: initValue,
    select: true,
  })

  return list.map((item: any) => ({
    label: item.label,
    value: item.production_sn,
  }))
}
const processOptions = async ({ keyword = '' }: Record<string, any>) => {
  let quick_search = ''
  let initValue = ''
  let initKey = 'id'

  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '')
  } else {
    quick_search = keyword
  }

  const { list } = await getProcessList({
    quick_search: quick_search,
    page: 1,
    limit: 10000,
    initKey: initKey,
    initValue: initValue,
    select: true,
  })

  return list.map((item: any) => ({
    label: item.label,
    value: item.id,
  }))
}


/**
 * 选择生产制单时获取商品信息
 */
const getPlanGoodsData = async (production_sn: string) => {
  // 将列表清除
  if (gridApi) {
    gridApi.setGridOptions({
      data: [],
    })
  }

  if (!production_sn) {
    return false
  }

  // 请求数据
  const { sku_list } = await getPlanGoods({
    production_sn: production_sn,
  })

  if (gridApi && sku_list) {
    gridApi.setGridOptions({
      data: sku_list,
    })
  }
}

/**
 * 计算金额
 */
const computeAmount = (row: RowType) => {
  if (row.num && row.price) {
    row.amount = (Number(row.num) * Number(row.price)).toFixed(2)
  }else{
    row.amount = 0
  }
}

/**
 * 表格合计方法
 */
const getSummaries = (param: any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const values = data.map((item: any) => Number(item[column.property]))
    const columnNamesToExclude = ['num', 'amount']
    if (!values.every((value: number) => Number.isNaN(value)) && columnNamesToExclude.includes(column.property)) {
      sums[index] = `${values.reduce((prev: number, curr: number) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          let value = Number(prev) + Number(curr)
          return value.toFixed(2)
        } else {
          return prev
        }
      }, 0)}`
    } else {
      sums[index] = ''
    }
  })
  return [sums]
}

/**
 * 弹窗配置
 */
const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  appendToMain: true,
  fullscreen: true,
  showConfirmButton: false,
  showCancelButton: false,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      routerData.value = modalApi.getData<Record<string, any>>()
      mstockinId.value = 0
      formApi.setValues({})
      gridApi.setGridOptions({
        data: [],
      })
      Object.keys(keyword.value).forEach((key) => {
        keyword.value[key] = ''
      })

      if (routerData.value?.info?.id) {
        mstockinId.value = routerData.value?.info?.id
      }

      if (mstockinId.value) {
        fetchData()
        isDisabled.value = true
      } else {
        isDisabled.value = false
        // formApi.setState({ commonConfig: { disabled: false} })
        
      }
    }
  },
})

/**
 * 表格配置
 */
/**
 * 构建表格列配置，确保列的禁用状态随表单切换
 */
function createColumns(disabled: boolean): VxeGridProps<RowType>['columns'] {
  return [
    { type: 'seq', width: 60, title: '序号' },
    { field: 'goods_no', title: '货号', width: 120 },
    { field: 'goods_name', title: '货号名称', width: 180 },
    { field: 'color_code', title: '颜色编号', width: 100 },
    { field: 'color_name', title: '颜色', width: 100 },
    { field: 'size_name', title: '尺码', width: 80 },
    {
      field: 'num',
      title: '数量',
      width: 100,
      cellRender: {
        name: 'CellInput',
        props: { allowClear: true, disabled, onChange: computeAmount },
      },
    },
    {
      field: 'bad_num',
      title: '不合格数',
      width: 100,
      cellRender: { name: 'CellInput', props: { allowClear: true, disabled } },
    },
    {
      field: 'weight',
      title: '重量',
      width: 80,
      cellRender: { name: 'CellInput', props: { allowClear: true, disabled } },
    },
    {
      field: 'price',
      title: '价格',
      width: 100,
      cellRender: {
        name: 'CellInput',
        props: { allowClear: true, disabled, onChange: computeAmount },
      },
    },
    { field: 'amount', title: '金额', width: 100 },
    {
      field: 'remark',
      title: '备注',
      width: 200,
      editRender: { name: 'CellInput', props: { allowClear: true, disabled } },
    },
  ]
}

const gridOptions: VxeGridProps<RowType> = {
  pagerConfig: {
    enabled: false,
  },
  columns: createColumns(isDisabled.value),
  exportConfig: {},
  editConfig: {
    mode: 'cell',
    trigger: 'click',
  },
  height: '440px',
  keepSource: false,
  data: [],
  showOverflow: false,
  showFooter: true,
  footerMethod: getSummaries,
}


/**
 * 监听禁用状态变化
 */
 watch(isDisabled, (val) => {
  formApi.setState({ commonConfig: { disabled: val } })
  if (gridApi) {
    gridApi.setGridOptions({
      columns: createColumns(val),
    })
  }
})

/**
 * 切换编辑状态
 */
const handleUpdate = async () => {
  isDisabled.value = !isDisabled.value

}

/**
 * 审核/反审
 */
const handleAudit = async (type: string) => {
  modalApi.lock()
  try {
    if (type === 'audit') {
      await AuditMstockIn({ ids: [mstockinId.value] })
    } else {
      await ReverseMstockIn({ ids: [mstockinId.value] })
    }
    message.success('操作成功')
    emit('fetchData')
    modalApi.close()
  } finally {
    modalApi.lock(false)
  }
}

/**
 * 提交表单
 */
async function onSubmit() {
  const { valid } = await formApi.validate()
  if (valid) {
    let saveData = await formApi.getValues()
    if (gridApi) {
      const tableData = gridApi.grid.getData()
      saveData.sku_list = tableData
    }
    modalApi.lock()
    try {
      if (mstockinId.value) {
        await doMstockinEdit({ ...saveData, id: mstockinId.value })
      } else {
        await doMstockinAdd(saveData)
      }
      message.success('保存成功')
      emit('fetchData')
      modalApi.close()
    } finally {
      modalApi.lock(false)
    }
  }
}
const handleAddPlanid = async () => {
  // message.success('添加生产制单')
  PlanApi.setData({ query: { params: { production_sn: null } }, selectType: 'radio' }).open()
}

/**
 * 关闭弹窗
 */
const handleClose = async () => {
  modalApi.close()
}

/**
 * 表单配置
 */
const [Form, formApi] = useVbenForm({
  commonConfig: {
    disabled: isDisabled.value,
    componentProps: {
      class: 'w-full',
    },
  },
  showDefaultActions: false,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      fieldName: 'record_sn',
      label: '入库单号',
      componentProps: {
        disabled: true,
        placeholder: '自动生成',
      },
    },
    {
      component: 'DatePicker',
      fieldName: 'record_date',
      label: '单据日期',
      defaultValue: dayjs().format('YYYY-MM-DD'),
      componentProps: {
        class: 'w-full',
        type: 'date',
        clearable: true,
        placeholder: '请选择单据日期',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        disabledDate: (current: any) => {
          // 不允许选择三天前之前的数据
          return current && current <= dayjs().subtract(4, 'day').startOf('day')
        },
      },
      rules: 'required',
    },
    {
      component: 'ApiSelect',
      fieldName: 'Planid',
      label: '生产制单',
      formItemClass: 'col-span-2',
      componentProps: () => ({
        api: planOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.Planid = value
        }, 300),
        params: {
          keyword: keyword.value.Planid || undefined,
        },
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        allowClear: true,
        maxTagCount: 'responsive',
        visibleEvent: 'onFocus',
        onChange: (value: string) => getPlanGoodsData(value),
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.Planid = ''
        },
        placeholder: '按生产制单号/货号/简码搜索',
        class: 'min-w-0 flex-1',
      }),
      rules: 'selectRequired',
      suffix: () => h(Button, { onClick: handleAddPlanid, class: 'w-15' }, () => '选择'),
    },
    {
      component: 'ApiSelect',
      fieldName: 'process_id',
      label: '加工工序',
      componentProps: {
        api: processOptions,
        placeholder: '按工序名称搜索',
        showSearch: true,
        filterOption: (input: string, option: any) => {
          return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
        },
      },
      rules: 'selectRequired',
    },
    {
      component: 'ApiSelect',
      fieldName: 'supply_id',
      label: '加工厂',
      componentProps: () => ({
        api: supplyOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.supply_id = value
        }, 300),
        params: {
          keyword: keyword.value.supply_id || undefined,
        },
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        allowClear: true,
        maxTagCount: 'responsive',
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.supply_id = ''
        },
        placeholder: '按加工厂简称/全称/编号搜索',
      }),
      rules: 'selectRequired',
    },
    {
      component: 'ApiSelect',
      fieldName: 'warehouse_id',
      label: '仓库编号',
      componentProps: () => ({
        api: warehouseOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.warehouse_id = value
        }, 300),
        params: {
          keyword: keyword.value.warehouse_id || undefined,
        },
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        allowClear: true,
        maxTagCount: 'responsive',
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.warehouse_id = ''
        },
        placeholder: '按仓库编号/名称搜索',
      }),
      rules: 'selectRequired',
    },
    {
      component: 'Input',
      fieldName: 'Manualid',
      label: '手工单号',
      componentProps: {
        placeholder: '请输入手工单号',
        clearable: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'Remark',
      label: '备注',
      formItemClass: 'col-span-2',
      componentProps: {
        type: 'textarea',
        placeholder: '请输入备注',
        rows: 2,
      },
    },
  ],
  wrapperClass: 'grid grid-cols-6',
})

/**
 * 表格组件
 */
const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
})

const [PlanModal, PlanApi] = useVbenModal({
  connectedComponent: Plan,
})
const shareData = (res: any) => {
  console.log('shareData', res)
  if (res.shareType && res.shareType === 'plan') {
    doPlanList(res)
  }
  return
}
const doPlanList = (res: any) => {
  if (res.list && res.list.length > 0) {
    formApi.setFieldValue('Planid', res.list[0].value)
    keyword.value.Planid = res.list[0].value
    getPlanGoodsData(res.list[0].value)
  }
}
</script>
<template>
  <Modal title="物料入库单">
    <div class="">
      <Form />
      <div class="mt-1">
        <!-- <h3 class="text-lg font-medium mb-4">商品列表</h3> -->
        <Grid>
  
        </Grid>
      </div>

      <div v-if="formData.id > 0" class="mt-6 border rounded p-4">
        <div class="grid grid-cols-3 gap-4">
          <div>
            <span class="font-medium">制单人：</span>
            {{ formData.Operator_realname }}
          </div>
          <div>
            <span class="font-medium">审核人：</span>
            {{ formData.PostUser_realname }}
          </div>
          <div>
            <span class="font-medium">最后修改人：</span>
            {{ formData.ModifyUser_realname }}
          </div>
          <div>
            <span class="font-medium">制单时间：</span>
            {{ formData.InputDate }}
          </div>
          <div>
            <span class="font-medium">审核时间：</span>
            {{ formData.PostedDate }}
          </div>
          <div>
            <span class="font-medium">最后修改时间：</span>
            {{ formData.ModifyDate }}
          </div>
        </div>
      </div>
    </div>
    <template #prepend-footer>
      <Button @click="handleClose()">取消</Button>
      <template v-if="mstockinId">
        <Button class="bg-[#f56c6c] text-white" @click="handleAudit(formData.Posted ? 'reverse' : 'audit')">
          {{ formData.Posted ? '反审' : '审核' }}
        </Button>
        <Button v-if="!formData.Posted && isDisabled" class="bg-[#f0a62f] text-[#fff]" @click="handleUpdate()">修改</Button>
      </template>
      <Button v-if="!isDisabled || !mstockinId" type="primary" @click="onSubmit()">保存</Button>
    </template>
    <PlanModal @share-data="shareData" />
  </Modal>
</template>

<style lang="scss" scoped>
.fixed-width-select {
  width: 160px;
}
</style>
